using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.ComponentModel;
using System.Data;
using ACME.Northwind.DataTransfer;
using ACME.Northwind.Business.Objects;
using Widgetsphere.Core.DataAccess;
using System.Linq.Expressions;
using ACME.Northwind.Business.LINQ;
using Widgetsphere.Core.Util;

namespace ACME.Northwind.DALProxy.Extensions
{
	/// <summary>
	/// This is a set of extensions for the Employee DAL/DTO object
	/// </summary>
	public static partial class EmployeeExtension
	{
		#region Fill DAL

		/// <summary>
		/// Populate a DAL object from its corresponding DTO.
		/// </summary>
		/// <param name="item">The empty DAL object.</param>
		/// <param name="dtoItem">The source DTO to load.</param>
		public static void Fill(this Employee item, EmployeeDTO dtoItem)
		{
			if (dtoItem == null) throw new Exception("The Employee DTO cannot be null.");
			if (item == null) throw new Exception("The Employee item cannot be null.");
			DataRow dr = ((DataRow)((IWrappingClass)item).WrappedClass);
			if (dtoItem.TitleOfCourtesy == null) dr["TitleOfCourtesy"] = System.DBNull.Value;
			else dr["TitleOfCourtesy"] = dtoItem.TitleOfCourtesy;
			if (dtoItem.Title == null) dr["Title"] = System.DBNull.Value;
			else dr["Title"] = dtoItem.Title;
			if (dtoItem.ReportsTo == null) dr["ReportsTo"] = System.DBNull.Value;
			else dr["ReportsTo"] = dtoItem.ReportsTo;
			if (dtoItem.Region == null) dr["Region"] = System.DBNull.Value;
			else dr["Region"] = dtoItem.Region;
			if (dtoItem.PostalCode == null) dr["PostalCode"] = System.DBNull.Value;
			else dr["PostalCode"] = dtoItem.PostalCode;
			if (dtoItem.PhotoPath == null) dr["PhotoPath"] = System.DBNull.Value;
			else dr["PhotoPath"] = dtoItem.PhotoPath;
			if (dtoItem.Photo == null) dr["Photo"] = System.DBNull.Value;
			else dr["Photo"] = dtoItem.Photo;
			if (dtoItem.Notes == null) dr["Notes"] = System.DBNull.Value;
			else dr["Notes"] = dtoItem.Notes;
			dr["LastName"] = dtoItem.LastName;
			if (dtoItem.HomePhone == null) dr["HomePhone"] = System.DBNull.Value;
			else dr["HomePhone"] = dtoItem.HomePhone;
			if (dtoItem.HireDate == null) dr["HireDate"] = System.DBNull.Value;
			else dr["HireDate"] = dtoItem.HireDate;
			dr["FirstName"] = dtoItem.FirstName;
			if (dtoItem.Extension == null) dr["Extension"] = System.DBNull.Value;
			else dr["Extension"] = dtoItem.Extension;
			dr["EmployeeID"] = dtoItem.EmployeeId;
			if (dtoItem.Country == null) dr["Country"] = System.DBNull.Value;
			else dr["Country"] = dtoItem.Country;
			if (dtoItem.City == null) dr["City"] = System.DBNull.Value;
			else dr["City"] = dtoItem.City;
			if (dtoItem.BirthDate == null) dr["BirthDate"] = System.DBNull.Value;
			else dr["BirthDate"] = dtoItem.BirthDate;
			if (dtoItem.Address == null) dr["Address"] = System.DBNull.Value;
			else dr["Address"] = dtoItem.Address;
		}

		#endregion

		#region Fill DTO

		/// <summary>
		/// Populate a DTO object collection from its corresponding DAL object collection.
		/// </summary>
		/// <param name="list">The destination DTO collection.</param>
		/// <param name="employeeCollection">The source DAL collection.</param>
		public static void Fill(this List<EmployeeDTO> list, EmployeeCollection employeeCollection)
		{
			if (employeeCollection == null) throw new Exception("The Employee collection cannot be null.");
			if (list == null) list = new List<EmployeeDTO>();
			foreach (Employee item in employeeCollection)
			{
				EmployeeDTO newItem = new EmployeeDTO();
				newItem.Fill(item);
				list.Add(newItem);
			}
		}

		/// <summary>
		/// Populate a DTO object from its corresponding DAL object.
		/// </summary>
		/// <param name="item">The source DAL object.</param>
		/// <param name="dtoItem">The empty DTO to load.</param>
		public static void Fill(this EmployeeDTO dtoItem, Employee item)
		{
			if (dtoItem == null) throw new Exception("The Employee DTO cannot be null.");
			if (item == null) throw new Exception("The Employee item cannot be null.");
			dtoItem.TitleOfCourtesy = item.TitleOfCourtesy;
			dtoItem.Title = item.Title;
			dtoItem.ReportsTo = item.ReportsTo;
			dtoItem.Region = item.Region;
			dtoItem.PostalCode = item.PostalCode;
			dtoItem.PhotoPath = item.PhotoPath;
			dtoItem.Photo = item.Photo;
			dtoItem.Notes = item.Notes;
			dtoItem.LastName = item.LastName;
			dtoItem.HomePhone = item.HomePhone;
			dtoItem.HireDate = item.HireDate;
			dtoItem.FirstName = item.FirstName;
			dtoItem.Extension = item.Extension;
			dtoItem.EmployeeId = item.EmployeeId;
			dtoItem.Country = item.Country;
			dtoItem.City = item.City;
			dtoItem.BirthDate = item.BirthDate;
			dtoItem.Address = item.Address;
			dtoItem.CreatedDate = item.CreatedDate;
			dtoItem.CreatedBy = item.CreatedBy;
			dtoItem.ModifiedDate = item.ModifiedDate;
			dtoItem.ModifiedBy = item.ModifiedBy;
		}

		#endregion

		#region RunSelect

		/// <summary>
		/// Select all objects from store.
		/// </summary>
		public static void RunSelect(this List<EmployeeDTO> list)
		{
			if (list == null) list = new List<EmployeeDTO>();
			EmployeeCollection retval = EmployeeCollection.RunSelect();
			foreach (Employee item in retval)
			{
				EmployeeDTO newItem = new EmployeeDTO();
				newItem.Fill(item);
				list.Add(newItem);
			}
		}

		/// <summary>
		/// Using the specified Where expression, execute a query against the database to return a result set.
		/// </summary>
		public static void RunSelect(this List<EmployeeDTO> list, Expression<Func<EmployeeQuery, bool>> where)
		{
			if (list == null) list = new List<EmployeeDTO>();
			list.Fill(EmployeeCollection.RunSelect(where));
		}

		#endregion

		#region RunSelect Paged

		/// <summary>
		/// Using the specified Where expression, execute a query against the database to return a paged result set.
		/// </summary>
		public static PagedQueryResults<EmployeeDTO> RunSelect(this List<EmployeeDTO> list, string pageSize, string page, string sortOrder, string sortColumn, string linq)
		{
			if (list == null) list = new List<EmployeeDTO>();
			#region Setup Variables and Error Check
			int po;
			int rpp;

			if (!int.TryParse(page, out po)) throw new Exception("The page number number is not a valid integer!");
			if (po < 1) po = 1;

			if (!int.TryParse(pageSize, out rpp)) throw new Exception("The page size is not a valid integer!");
			if (rpp < 1) rpp = 1;

			Employee.FieldNameConstants sortField;
			try
			{
				sortField = (Employee.FieldNameConstants)Enum.Parse(typeof(Employee.FieldNameConstants), sortColumn);
			}
			catch
			{
				throw new Exception("The sort field is not valid!");
			}

			bool ascending = (sortOrder.ToLower() == "asc" || sortOrder.ToLower() == "ascending");
			#endregion

			PagedQueryResults<EmployeeDTO> retVal = new PagedQueryResults<EmployeeDTO>();
			EmployeePaging paging = new EmployeePaging();
			paging.RecordsperPage = rpp;
			paging.PageIndex = po;
			paging.OrderByList.Add(new EmployeePagingFieldItem(sortField, ascending));

			EmployeeCollection dalList = null;
			if (string.IsNullOrEmpty(linq))
			{
				dalList = EmployeeCollection.RunSelect(x => true, paging);
			}
			else
			{
				System.Reflection.MethodInfo method = LINQDynamicCompile.GetLINQMethodPaged(linq, "ACME.Northwind.Business", "Employee");
				dalList = (EmployeeCollection)method.Invoke(null, new object[] { paging });
			}

			if (list == null) list = new List<EmployeeDTO>();
			foreach (Employee item in dalList)
			{
				EmployeeDTO newItem = new EmployeeDTO();
				newItem.Fill(item);
				list.Add(newItem);
			}

			retVal.CurrentPage = paging.PageIndex;
			double totalPages = Math.Ceiling((double)paging.RecordCount / (double)paging.RecordsperPage);
			retVal.TotalPages = (int)totalPages;
			retVal.TotalRecords = paging.RecordCount;
			retVal.GridData = list;

			return retVal;
		}

		#endregion

		#region RunSelect Paged

		/// <summary>
		/// Using the specified Where expression, execute a query against the database to return a result set.
		/// </summary>
		public static void RunSelect(this List<EmployeeDTO> list, string linq)
		{
			if (list == null) list = new List<EmployeeDTO>();

			EmployeeCollection dalList = null;
			if (string.IsNullOrEmpty(linq))
			{
				dalList = EmployeeCollection.RunSelect(x => true);
			}
			else
			{
				System.Reflection.MethodInfo method = LINQDynamicCompile.GetLINQMethodAll(linq, "ACME.Northwind.Business", "Employee");
				dalList = (EmployeeCollection)method.Invoke(null, new object[] { });
			}

			if (list == null) list = new List<EmployeeDTO>();
			foreach (Employee item in dalList)
			{
				EmployeeDTO newItem = new EmployeeDTO();
				newItem.Fill(item);
				list.Add(newItem);
			}
		}

		#endregion

		#region Persist

		/// <summary>
		/// Persists this object to store.
		/// </summary>
		public static EmployeeDTO Persist(this EmployeeDTO employee)
		{
			if (employee == null) throw new Exception("The Employee DTO cannot be null.");
			//Find this object and if not exists, create a new one
			Employee newItem = null;
			EmployeeCollection newCollection = null;

			bool isIdentityChecked = false;
			isIdentityChecked = true;
			if(isIdentityChecked)
			{
				if (employee.EmployeeId > 0)
				{
					newItem = ACME.Northwind.Business.Objects.Employee.SelectUsingPK(employee.EmployeeId);
					newCollection = newItem.ParentCollection;
				}
				else
				{
					if (employee.EmployeeId == 0) employee.EmployeeId = -1;
					newCollection = new EmployeeCollection();
					newItem = newCollection.NewItem();
				}
			}
			else
			{
				newItem = ACME.Northwind.Business.Objects.Employee.SelectUsingPK(employee.EmployeeId);
				if (newItem == null)
				{
					newCollection = new EmployeeCollection();
					newItem = newCollection.NewItem();
				}
				else
				{
					newCollection = newItem.ParentCollection;
				}
			}

			//Populate the DAL and perist
			newItem.Fill(employee);
			if (!newItem.IsParented) newCollection.AddItem(newItem);
			newCollection.Persist();

			//Re-populate the passed-in object from the DAL
			employee.Fill(newItem);
			return employee;
		}

		/// <summary>
		/// Persists this collection to store.
		/// </summary>
		public static bool Persist(this List<EmployeeDTO> employeeList)
		{
			if (employeeList == null) throw new Exception("The Employee DTO list cannot be null.");
			//Get all objects from the database that match PK
			EmployeeCollection employeeCollection = new EmployeeCollection();
			List<EmployeePrimaryKey> keyList = new List<EmployeePrimaryKey>();
			foreach (EmployeeDTO dto in employeeList)
			{
				keyList.Add(new EmployeePrimaryKey(dto.EmployeeId));
			}			
			employeeCollection.SubDomain.AddSelectCommand(new ACME.Northwind.Business.SelectCommands.EmployeeSelectByPks(keyList));
			employeeCollection.SubDomain.RunSelectCommands();

			//Now find and populate the objects for saving
			foreach (EmployeeDTO dto in employeeList)
			{
				Employee employee = (from x in (IEnumerable<Employee>)employeeCollection
					where x.EmployeeId == dto.EmployeeId
					select x).FirstOrDefault();

				if (employee == null) employee = employeeCollection.NewItem();
				employee.Fill(dto);
				if (!employee.IsParented) employeeCollection.AddItem(employee);
			}
			employeeCollection.Persist();

			//Re-populate the passed-in object from the DAL
			List<EmployeeDTO> deletedList = new List<EmployeeDTO>();
			foreach (EmployeeDTO dto in employeeList)
			{
				Employee employee = (from x in (IEnumerable<Employee>)employeeCollection
					where x.EmployeeId == dto.EmployeeId
					select x).FirstOrDefault();

				if (employee != null) dto.Fill(employee);
				else deletedList.Add(dto);
			}

			//Remove the items that are no longer there (if any)
			foreach (EmployeeDTO dto in deletedList)
			{
				employeeList.Remove(dto);
			}

			return true;
		}

		#endregion

		#region Employee Select by Column

		#endregion

		#region Employee SelectUsingPK

		/// <summary>
		/// Select a single object from this collection by its primary key.
		/// </summary>
		public static bool SelectUsingPK(this EmployeeDTO employee, int employeeid)
		{
			Employee item = ACME.Northwind.Business.Objects.Employee.SelectUsingPK(employeeid);
			if (item == null) return false;
			employee.Fill(item);
			return true;
		}

		#endregion

		#region Employee Select By Foreign Key

		/// <summary>
		/// Populate a 'Employee' DTO object collection from its relationship with the 'Employee' table.
		/// </summary>
		public static void SelectByEmployee(this List<EmployeeDTO> EmployeeList, int employeeid)
		{
			EmployeeCollection list = EmployeeCollection.RunSelect(x => x.ReportsTo == employeeid);
			foreach (Employee item in list)
			{
				EmployeeDTO newItem = new EmployeeDTO();
				newItem.Fill(item);
				EmployeeList.Add(newItem);
			}
		}

		#endregion

		#region Employee Delete

		/// <summary>
		/// Delete the specified item
		/// </summary>
		public static bool Delete(this EmployeeDTO employee)
		{
			Employee item = ACME.Northwind.Business.Objects.Employee.SelectUsingPK(employee.EmployeeId);
			if (item == null) return false;
			item.Delete();
			item.Persist();
			return true;
		}

		#endregion
	}

}
